﻿using System;
using System.Collections.Generic;
using System.Reactive.Concurrency;

namespace Badobo.Scheduler
{
    public class SchedulerTaskManager : IDisposable
    {
        private List<SchedulerTask> m_Tasks;
        private List<IDisposable> m_Schedulers;
        private bool m_Disposed;

        public SchedulerTaskManager()
        {
            m_Tasks = new List<SchedulerTask>();
            m_Schedulers = new List<IDisposable>();
        }

        public void RegisterSchedulerTask(ISchedulerTask task, SchedulerTaskSetting taskSetting)
        {
            m_Tasks.Add(new SchedulerTask {Task = task, TaskSettings = taskSetting});
        }

        public void Start()
        {
            foreach (SchedulerTask task in m_Tasks)
            {
                IScheduler scheduler = System.Reactive.Concurrency.Scheduler.NewThread;
                m_Schedulers.Add(scheduler.Schedule(TimeSpan.FromSeconds(task.TaskSettings.IntervalInSeconds), () => task.Run()));
            }
        }

        public void Stop()
        {
            if (m_Schedulers != null)
            {
                foreach (IDisposable scheduler in m_Schedulers)
                {
                    if (scheduler != null)
                    {
                        scheduler.Dispose();
                    }
                }

                m_Schedulers.Clear();
            }
        }

        public void Dispose()
        {
            if (!m_Disposed)
            {
                lock (this)
                {
                    Stop();
                    m_Schedulers = null;
                    m_Tasks = null;
                    m_Disposed = true;
                }
            }
        }

    }
}
